package com.linq.cool.common.log.aspect;


import com.alibaba.fastjson.JSON;
import com.linq.cool.api.domain.SysOperateLog;
import com.linq.cool.common.constants.CacheConstants;
import com.linq.cool.common.constants.UserConstants;
import com.linq.cool.common.core.utils.IpUtils;
import com.linq.cool.common.core.utils.JsonUtils;
import com.linq.cool.common.core.utils.ServletUtils;
import com.linq.cool.common.core.utils.StringUtils;
import com.linq.cool.common.log.annotation.Log;
import com.linq.cool.common.log.service.AsyncOperateLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: yqlin
 * @Date: 2020/12/29 17:08
 * @Description: 操作日志记录处理
 * @Version: 1.0.0
 */
@Aspect
@Component
@Slf4j
public class OperateLogAspect {
    @Autowired
    private AsyncOperateLogService asyncOperateLogService;

    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.linq.cool.common.log.annotation.Log)")
    public void operateLogPointCut() {

    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "operateLogPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleOperateLog(joinPoint, null, jsonResult);
    }


    protected void handleOperateLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try {
            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            Method method = methodSignature.getMethod();
            Log logAnnotation = method.getAnnotation(Log.class);
            if (logAnnotation != null) {
                // 数据库日志
                SysOperateLog operateLog = new SysOperateLog();
                HttpServletRequest request = ServletUtils.getRequest();
                operateLog
                        .setStatus(UserConstants.StateEnum.STATUS_NORMAL.getCode())
                        .setIp(IpUtils.getIpAddr(Objects.requireNonNull(request)))
                        .setJsonResult(JSON.toJSONString(jsonResult))
                        .setUrl(request.getRequestURI());
                String userId = request.getHeader(CacheConstants.DETAILS_USER_ID);
                if (StringUtils.isNotEmpty(userId)) {
                    operateLog.setCreator(Long.valueOf(userId)).setModifier(Long.valueOf(userId));
                }
                // 跑出异常
                if (e != null) {
                    operateLog
                            .setStatus(UserConstants.StateEnum.STATUS_DISABLE.getCode())
                            .setMessage(StringUtils.substring(e.getMessage(), 0, 2000));
                }
                // 类名
                String className = joinPoint.getTarget().getClass().getName();
                // 方法名
                String methodName = joinPoint.getSignature().getName();
                operateLog
                        .setMethod(className + "." + methodName + "()")
                        // 设置请求方式
                        .setRequestMethod(request.getMethod())
                        // 获取注解中对方法的描述信息 用于Controller层注解
                        .setBusinessType(logAnnotation.businessType().ordinal())
                        // 设置标题
                        .setModuleTitle(logAnnotation.moduleTitle())
                        // 设置操作人类别
                        .setOperatorType(logAnnotation.operatorType().ordinal());
                // 是否需要保存request，参数和值 获取请求的参数，放到log中
                if (logAnnotation.isSaveRequestParam()) {
                    String requestMethod = request.getMethod();
                    if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
                        String params = argsArrayToString(joinPoint.getArgs());
                        operateLog.setParam(StringUtils.substring(params, 0, 2000));
                    }
                }
                // 保存日志
                asyncOperateLogService.saveOperateLog(operateLog);
            }
        } catch (Exception ex) {
            log.error("Advance notification exception: {}", ex.getMessage());
        }
    }


    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (!isFilterObject(o)) {
                    try {
                        Object jsonObj = JsonUtils.printJson(o);
                        params.append(jsonObj.toString()).append(" ");
                    } catch (Exception ex) {
                        log.error(ex.getMessage());
                    }
                }
            }
        }
        return params.toString().trim();
    }


    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     *
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
    }
}
